package com.hankol.feature_wine_meal.adapter

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.RelativeLayout
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import com.baselibrary.Constants
import com.baselibrary.utils.GlideUtils
import com.baselibrary.utils.NumberUtils
import com.baselibrary.utils.ScreenUtils
import com.baselibrary.utils.TimeUtil
import com.baselibrary.view.banner.BannerConfig
import com.baselibrary.view.banner.Transformer
import com.baselibrary.view.banner.loader.GlideImageLoader
import com.hankol.feature_wine_meal.R
import com.hankol.feature_wine_meal.bean.FoodDetailsBean
import com.hankol.feature_wine_meal.bean.MainFood
import com.hankol.feature_wine_meal.databinding.ItemMaterialsUsedBinding
import com.hankol.feature_wine_meal.databinding.ItemWineDetailsHeadBinding
import com.hankol.feature_wine_meal.databinding.ItemWineDetailsRvStepBinding
import com.hankol.feature_wine_meal.databinding.ItemWineDetailsSkillBinding
import com.hankol.feature_wine_meal.viewmodel.WineMealViewModel
import com.transitionseverywhere.TransitionManager
import com.transitionseverywhere.extra.Scale

/**
 * @author: 关忆北、
 * @date: 2022/6/22
 * @Des：
 */
class WineDetailsAdapter(var activity: Activity, var mViewModel: WineMealViewModel, var shareListener: OnShareClickListener) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    private var mBean: FoodDetailsBean? = null

    @SuppressLint("NotifyDataSetChanged")
    fun setData(bean: FoodDetailsBean) {
        this.mBean = null
        this.mBean = bean
        this.notifyDataSetChanged()
    }

    companion object {
        const val TYPE_MATERIALS_HEAD = 0//头部
        const val TYPE_MATERIALS_USED = 1//材料
        const val TYPE_MATERIALS_ASSIST = 2//辅料
        const val TYPE_STEP = 3//步骤+成品图
        const val TYPE_SKILL = 4//技巧+分享
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val from = LayoutInflater.from(parent.context)
        return when (viewType) {
            TYPE_MATERIALS_HEAD -> {
                val binding = DataBindingUtil.inflate<ItemWineDetailsHeadBinding>(from, R.layout.item_wine_details_head, parent, false)
                HeadHolder(binding, mViewModel)
            }
            TYPE_MATERIALS_USED -> {
                val materialsUsedBinding = DataBindingUtil.inflate<ItemMaterialsUsedBinding>(from, R.layout.item_materials_used, parent, false)
                materialsUsedBinding.tvMaterialsUsed.text = "主料"
                materialsUsedBinding.llMaterialsOpen.visibility = View.GONE
                materialsUsedBinding.tvMaterialsUsedPerson.visibility = View.VISIBLE
                MaterialsUsedHolder(materialsUsedBinding, TYPE_MATERIALS_USED)
            }
            TYPE_MATERIALS_ASSIST -> {
                val materialsUsedBinding = DataBindingUtil.inflate<ItemMaterialsUsedBinding>(from, R.layout.item_materials_used, parent, false)
                materialsUsedBinding.tvMaterialsUsed.text = "辅料"
                materialsUsedBinding.llMaterialsOpen.visibility = View.VISIBLE
                materialsUsedBinding.tvMaterialsUsedPerson.visibility = View.GONE
                MaterialsUsedHolder(materialsUsedBinding, TYPE_MATERIALS_ASSIST)
            }
            TYPE_STEP -> {
                val stepBinding = DataBindingUtil.inflate<ItemWineDetailsRvStepBinding>(from, R.layout.item_wine_details_rv_step, parent, false)
                StepHolder(stepBinding, mViewModel)
            }
            else -> {
                val materialsUsedBinding = DataBindingUtil.inflate<ItemWineDetailsSkillBinding>(from, R.layout.item_wine_details_skill, parent, false)
                SkillHolder(materialsUsedBinding, shareListener, mViewModel, parent.context.applicationContext)
            }
        }

    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (holder) {
            is HeadHolder -> {
                mBean?.let {
                    holder.setData(it)
                }
            }
            is MaterialsUsedHolder -> {
                mBean?.let {
                    holder.setData(it)
                }
            }
            is StepHolder -> {
                mBean?.let {
                    holder.setData(it)
                }
            }
            is SkillHolder -> {
                mBean?.let {
                    holder.setData(it)
                }
            }
        }
    }

    override fun getItemCount(): Int {
        return 5
    }

    override fun getItemViewType(position: Int): Int {
        return position
    }


    class MaterialsUsedHolder(val dataBinding: ItemMaterialsUsedBinding, var type: Int) : WineMealDetailsBaseHolder(dataBinding.root) {
        var materialsInfoAdapter: MaterialsInfoAdapter = MaterialsInfoAdapter()
        var originalList: ArrayList<MainFood> = arrayListOf()//默认显示的集合数据
        var laterList: ArrayList<MainFood> = arrayListOf()//点击展开后需要addData的数据集合
        override fun setData(bean: FoodDetailsBean) {
            laterList.clear()
            originalList.clear()
            dataBinding.rvMaterialsUsedList.adapter = materialsInfoAdapter
            if (type == TYPE_MATERIALS_ASSIST) {
                //辅料
                changeList(bean)
                materialsInfoAdapter.setNewData(originalList)

            } else {
                //主料
                materialsInfoAdapter.setNewData(bean.mainFood)
            }

            dataBinding.tvMaterialsUsedPerson.text = bean.usersNum
            dataBinding.llMaterialsOpen.setOnClickListener {
                materialsInfoAdapter.addData(laterList)
                TransitionManager.beginDelayedTransition(dataBinding.transitionsContainer, Scale())
                TransitionManager.beginDelayedTransition(dataBinding.transitionsContainer)
                dataBinding.llMaterialsOpen.visibility = View.GONE
            }
        }

        fun changeList(bean: FoodDetailsBean) {
            if (bean.secondFood.size > 4) {
                for (index in bean.secondFood.indices) {
                    if (originalList.size < 4) {
                        originalList.add(bean.secondFood[index])
                        continue
                    }
                    laterList.add(bean.secondFood[index])
                }
                dataBinding.llMaterialsOpen.visibility = View.VISIBLE
            } else {
                originalList.addAll(bean.secondFood)
                dataBinding.llMaterialsOpen.visibility = View.GONE
            }
        }
    }


    class HeadHolder(val dataBinding: ItemWineDetailsHeadBinding, var mViewModel: WineMealViewModel) : WineMealDetailsBaseHolder(dataBinding.root) {
        @SuppressLint("SetTextI18n")
        override fun setData(bean: FoodDetailsBean) {
            changeImgHeight()
            dataBinding.ivWineDetailsTitle.text = bean.name
            dataBinding.tvWineDetailsDes.text = bean.desc
            dataBinding.tvWineDetailsIntroduce.setContent(bean.coverDesc)
            dataBinding.DifficultyLevelView.setData(bean)
            dataBinding.tvWineDetailsCollectionNum.text = "${NumberUtils.formatBigNum(bean.favoriteNum.toString())} 收藏 · ${NumberUtils.formatBigNum((bean.viewNum + bean.configViewNum).toString())} 浏览 · ${TimeUtil.fromToday(bean.startTime)}"

            dataBinding.corcleAuthorName.text = bean.authorName
            GlideUtils.loadUserHead(dataBinding.root.context.applicationContext, bean.authorIcon, dataBinding.corcleAuthorHead)
            GlideUtils.loadImg_228(dataBinding.root.context.applicationContext, bean.cover, dataBinding.ivWineDetailsCover)
            dataBinding.ivWineDetailsCover.setOnClickListener {
                mViewModel.browseImg(arrayListOf(bean.cover), 0)
            }
        }

        fun changeImgHeight() {
            val params: LinearLayout.LayoutParams = dataBinding.rlWineDetailsCover.layoutParams as LinearLayout.LayoutParams
            params.height = (ScreenUtils.getScreenWidth() / Constants.DYNAMIC_PICTURE_SCALE).toInt()
            dataBinding.rlWineDetailsCover.layoutParams = params
        }

    }


    class StepHolder(val dataBinding: ItemWineDetailsRvStepBinding, var mViewModel: WineMealViewModel) : WineMealDetailsBaseHolder(dataBinding.root) {
        val adapter: WineDetailsStepAdapter by lazy { WineDetailsStepAdapter((ScreenUtils.getScreenWidth() / Constants.FOLLOW_PICTURE_SCALE).toInt()) }
        override fun setData(bean: FoodDetailsBean) {
            dataBinding.rvWineDetailsStep.adapter = adapter
            adapter.setNewData(bean.steps)

            adapter.setOnItemChildClickListener { adapter, _, position ->
                val any = adapter.data[position]
                if (any is MainFood) {
                    mViewModel.browseImg(arrayListOf(any.cover), 0)
                }
            }
        }
    }

    class SkillHolder(val dataBinding: ItemWineDetailsSkillBinding, val shareListener: OnShareClickListener, var mViewModel: WineMealViewModel, val context: Context) : WineMealDetailsBaseHolder(dataBinding.root) {
        var adapter: FinishedProductAdapter = FinishedProductAdapter()
        var currentPage = 1
        override fun setData(bean: FoodDetailsBean) {
            setVpHeight()
            dataBinding.tvWineDetailsSkill.text = bean.tips
            if (bean.resultPic.isNotEmpty()) {
                //GlideUtils
                adapter.setData(bean.resultPic)
                dataBinding.bannerFinishedProduct.setImages(bean.resultPic).setImageLoader(GlideImageLoader(1)).setBannerAnimation(Transformer.Default).isAutoPlay(false).setIndicatorGravity(BannerConfig.CENTER).setOnBannerListener {
                            mViewModel.browseImg(bean.resultPic, it)
                        }.start()

                dataBinding.bannerFinishedProduct.visibility = View.VISIBLE
            } else {
                dataBinding.bannerFinishedProduct.visibility = View.GONE
            }

            adapter.setOnClickListener(object : FinishedProductAdapter.OnImgClickListener {
                override fun onClick(list: List<String>, position: Int) {
                    mViewModel.browseImg(ArrayList(list), position)
                }

            })
            dataBinding.includeShare.tvShare2Wx.setOnClickListener {
                shareListener.onWxShareClick()
            }
            dataBinding.includeShare.tvShare2WxCircle.setOnClickListener {
                shareListener.onWxCircleShareClick()
            }
            /* dataBinding.vpFinishedProduct.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
                 override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {

                 }

                 override fun onPageSelected(position: Int) {
                     currentPage = position
                     dataBinding.pivFinishedProduct.setCurrentShowView((position - 1 + dataBinding.pivFinishedProduct.count) % dataBinding.pivFinishedProduct.count)

                 }

                 override fun onPageScrollStateChanged(state: Int) {
 //验证当前的滑动是否结束


                     //验证当前的滑动是否结束
                     if (state == ViewPager.SCROLL_STATE_IDLE) {
                         //滑动动画做完的时候
                         if (currentPage == 0) {
                             dataBinding.vpFinishedProduct.setCurrentItem(adapter.count - 2, false) //切换，不要动画效果
                         } else if (currentPage == adapter.count - 1) {
                             dataBinding.vpFinishedProduct.setCurrentItem(1, false) //切换，不要动画效果
                         }
                     }
                 }

             })*/
        }

        private fun setVpHeight() {
            val params: RelativeLayout.LayoutParams = dataBinding.bannerFinishedProduct.layoutParams as RelativeLayout.LayoutParams
            params.height = (ScreenUtils.getScreenWidth() / Constants.FOLLOW_PICTURE_SCALE).toInt()
            dataBinding.bannerFinishedProduct.layoutParams = params
        }

    }

    abstract class WineMealDetailsBaseHolder(view: View) : RecyclerView.ViewHolder(view) {
        abstract fun setData(bean: FoodDetailsBean)
    }

    interface OnShareClickListener {
        fun onWxShareClick()
        fun onWxCircleShareClick()
    }
}